package com.ssm.subject.application.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * feign拦截器，调用方进行拦截, 调用方的请求头无法进行传递
 */
@Component
public class FeignRequestInterceptor implements RequestInterceptor {
    /**
     * RequestContextHolder.getRequestAttributes()：从当前线程的 ThreadLocal 中获取请求上下文信息，并将其作为 RequestAttributes 类型返回
     * ServletRequestAttributes 继承自 RequestAttributes，用于存储和管理与 Servlet 请求相关的属性信息。
     *
     * requestAttributes.getRequest()：获取 HttpServletRequest 对象，通过这个对象可以访问到请求的详细信息，如请求头、请求参数、请求方法、请求 URI 等。
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        if(Objects.nonNull(request)) {
            String loginId = request.getHeader("loginId");
            if(!StringUtils.isEmpty(loginId)) {
                requestTemplate.header("loginId", loginId);
            }
        }
    }
}
